package com.example.test7

import android.Manifest
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import kotlinx.coroutines.channels.Channel
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity(), ServiceConnection {
    var binder: MusicService.MusicBinder? = null
    private var isRunning = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val seekBar = findViewById<SeekBar>(R.id.seekBar)

        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.READ_MEDIA_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) { // 检查权限
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.READ_MEDIA_AUDIO),
                0
            )   // 请求权限
        } else {
            startMusicService() // 启动音乐播放服务
        }

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {    // 进度条监听
            override fun onProgressChanged(
                seekBar: SeekBar?,
                progress: Int,
                fromUser: Boolean
            ) {
                if (fromUser) {   // 用户拖动进度条
                    binder?.currentPosition = progress  // 设置音乐播放位置
                }
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {  // 开始拖动进度条
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {   // 停止拖动进度条
            }
        })

        startNotification()
    }

    fun startMusicService() {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1)
        startService(intent)
        bindService(intent, this, Context.BIND_AUTO_CREATE)
    }

    fun onPlay(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 1)
        startService(intent)
    }

    fun onPause(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 2)
        startService(intent)
    }

    fun onStop(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 3)
        startService(intent)
    }

    fun onNext(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 4)
        startService(intent)
    }

    fun onPrev(v: View) {
        val intent = Intent(this, MusicService::class.java)
        intent.putExtra(MusicService.Commond, 5)
        startService(intent)
    }


    override fun onRequestPermissionsResult(    // 请求权限结果
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0 && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            startMusicService()
        } else {
            // Handle the case where permission is not granted
            Log.e("MainActivity", "Permission not granted")
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        isRunning = false
        unbindService(this)
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {  // 服务连接
        val seekBar = findViewById<SeekBar>(R.id.seekBar)
        val textView_mn = findViewById<TextView>(R.id.textView_mn)
        val textView_count = findViewById<TextView>(R.id.textView_count)

        binder = service as MusicService.MusicBinder
        startNotification()
        isRunning = true
        thread {
            while (isRunning && binder != null) {
                Thread.sleep(1000)
                runOnUiThread {      // 更新UI
                    seekBar.max = binder!!.duration// 设置进度条最大值
                    seekBar.progress = binder!!.currentPosition// 设置进度条当前值
                    textView_mn.text = binder!!.musicName// 设置音乐名
                    textView_count.text = "${binder!!.currentIndex + 1}/${binder!!.size}"// 设置音乐序号
                }
            }
        }
    }

    override fun onServiceDisconnected(name: ComponentName?) {
        binder = null
    }


    fun startNotification() {        // 启动通知
        val Channel_ID = "my channel"
        val Notification_ID = 1
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder: Notification.Builder

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val notificationChannel =
                NotificationChannel(Channel_ID, "TEST", NotificationManager.IMPORTANCE_DEFAULT)
            notificationManager.createNotificationChannel(notificationChannel)
            builder = Notification.Builder(this, Channel_ID)
        } else {
            builder = Notification.Builder(this)
        }

        val intent2 = Intent(this, MainActivity::class.java)  // 点击通知后打开的Activity
        val pendingIntent =
            PendingIntent.getActivity(this, 1, intent2, PendingIntent.FLAG_MUTABLE)    //定义延迟意图
        //PendingIntent.FLAG_UPDATE_CURRENT在API版本31中已弃用，使用PendingIntent.FLAG_MUTABLE代替
        val notification = builder.setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("音乐播放器")
            .setContentText(binder?.musicName ?: "未知歌曲")
            .setContentIntent(pendingIntent)  // 设置点击通知后可以回到主界面
            .setAutoCancel(true)    // 点击通知后自动取消
            .build() // 构建通知

        notificationManager.notify(Notification_ID, notification)
    }

}